<?php
namespace app\common\service;

use app\common\model\User as UserModel;
use think\Session;

class User {

    public function login($account,$password){
        $loginUserKey = config("sessionKey.loginUserKey");
        $user = UserModel::get(['account'=>$account,'password'=>$this->encryptPassword($password)]);
        if($user){
            Session::set($loginUserKey,$user);
            return true;
        }
        return false;
    }

    public function updateLoginInfo($userInfo){
        $loginUserKey = config("sessionKey.loginUserKey");
        Session::set($loginUserKey,$userInfo);
    }


    public function getCurrentUser(){
        $loginUserKey = config("sessionKey.loginUserKey");
        $userInfo = Session::get($loginUserKey);
        return $userInfo;
    }


    public function logout(){
        $loginUserKey = config("sessionKey.loginUserKey");
        Session::delete($loginUserKey);
    }

    /**
     * 目前用这个
     * @param $password
     * @return string
     */
    private function encryptPassword($password){
        return md5($password);
    }



    public function getUsers(){
        $userModel = new UserModel();
        $users = $userModel->order('id desc')->paginate(20);
        return $users;
    }


    public function insert($data){

        if(!$data['password'] || strlen($data['password']) < 6)  return ['state'=>0,'message'=>"密码至少需要6位"];

        $data['password'] = $this->encryptPassword($data['password']);

        $userModel = new UserModel();

        $result = $userModel->validate('UserValidate.add')->save($data);

        if(false === $result){
            return ['state'=>0,'message'=>$userModel->getError()];
        }

        return ['state'=>1,'message'=>'','insertId'=>$userModel->id];
    }


    public function update($data){

        $userModel = new UserModel();

        if(intval($data['id']) <1){
            return ['state'=>0,'message'=>"参数错误"];
        }

        if(isset($data['password']) && strlen($data['password']) > 0 ){
            if(strlen($data['password']) < 6)  return ['state'=>0,'message'=>"密码至少需要6位"];
            $data['password'] = $this->encryptPassword($data['password']);
        }

        $result = $userModel->validate('UserValidate.edit')->save($data,['id'=>intval($data['id'])]);

        if(false === $result){
            return ['state'=>0,'message'=>$userModel->getError()];
        }

        return ['state'=>1,'message'=>''];
    }

    public function delete($ids){
        $userModel = new UserModel();

        $count = $userModel ->destroy($ids);

        return $count;
    }


    public function getUser($id){

        return UserModel::get(['id'=>$id]);

    }

}